/**
 * 
 */
package bingo.monitor.datasource;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 真实{@link DataSource}的代理，应用程序通过这个代理来操作
 * @author elvis
 */
public class DataSource implements javax.sql.DataSource {
	
	private static final AtomicInteger counter = new AtomicInteger();

	private final javax.sql.DataSource datasource;
	
	private final String name;
	
	public DataSource(javax.sql.DataSource datasource,String name){
		int index       = counter.incrementAndGet();
		this.datasource = datasource;
		this.name       = name == null || name.trim().equals("") ? String.valueOf(index) : name.trim();
	}
	
	/* (non-Javadoc)
	 * @see javax.sql.DataSource#getConnection()
	 */
	public Connection getConnection() throws SQLException {
		Connection connection = datasource.getConnection();
		
		DelegatingConnection proxiedConnection = new DelegatingConnection(this,connection);
		
		ConnectionMonitor.getMonitor().onConnectionOpen(proxiedConnection);
		
		return proxiedConnection;
	}

	/* (non-Javadoc)
	 * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String)
	 */
	public Connection getConnection(String username, String password) throws SQLException {
		return datasource.getConnection(username, password);
	}

	/* (non-Javadoc)
	 * @see javax.sql.DataSource#getLoginTimeout()
	 */
	public int getLoginTimeout() throws SQLException {
		return datasource.getLoginTimeout();
	}

	/* (non-Javadoc)
	 * @see javax.sql.DataSource#getLogWriter()
	 */
	public PrintWriter getLogWriter() throws SQLException {
		return datasource.getLogWriter();
	}

	/* (non-Javadoc)
	 * @see javax.sql.DataSource#setLoginTimeout(int)
	 */
	public void setLoginTimeout(int seconds) throws SQLException {
		datasource.setLoginTimeout(seconds);
	}

	/* (non-Javadoc)
	 * @see javax.sql.DataSource#setLogWriter(java.io.PrintWriter)
	 */
	public void setLogWriter(PrintWriter out) throws SQLException {
		datasource.setLogWriter(out);
	}

	/**
	 * @return 被代理的{@link DataSource}
	 */
	public javax.sql.DataSource getDataSource() {
		return datasource;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
}
